import threading
import os
import time
from time import sleep

import matplotlib.pyplot as plt
import cv2
from PyQt5 import QtWidgets, QtGui
import tcp_logic
import socket
import sys
from PyQt5.QtGui import *
from PIL import Image

from table_coordinate import Ui_table_history
from table_time import Ui_table_time
from person_location_show import locationUi
from time_place_registration import locationUi_2
import ctypes
import inspect


class MainWindow(tcp_logic.TcpLogic):
    def __init__(self, num):
        super(MainWindow, self).__init__(num)
        self.another_historical_data = None
        self.another_time_registration = None

        self.another_registration = None
        self.another_location = None
        self.link = False

        # 打开软件时默认获取本机ip
        self.click_get_ip()
        self.connect()

        self.tcp_client_Thread = None
        self.laser_tcp_client_Thread = None
        self.flush_thread = None
        self.radar_registration = None

    def connect(self):
        self.signal_write_rader_msg.connect(self.write_rader_msg)  # 雷达坐标文本浏览框触发信号
        self.signal_write_laser_msg.connect(self.write_laser_msg)  # 激光文本浏览框
        self.signal_write_fusion_msg.connect(self.write_fusion_msg)  # 文本浏览框

        self.signal_wall_rader_flush.connect(self.wall_rader_flush)  # 得到墙体数据 马上触发wall_rader_flush函数

        self.signal_radar_flush.connect(self.rader_flush)  # 雷达数据触发
        self.signal_laser_flush.connect(self.laser_flush)  # 激光数据触发
        self.signal_fusion_flush.connect(self.fusion_flush)  # 融合数据触发

        self.pushButton_link.clicked.connect(self.click_link)  # 连接网络按钮
        self.pushButton_unlink.clicked.connect(self.click_unlink)  # 断开网络按钮
        self.pushButton_get_ip.clicked.connect(self.click_get_ip)  # 重新获取IP按键
        self.pushButton_clear.clicked.connect(self.click_clear)  # 清除消息按钮
        self.pushButton_radar_turn_add.clicked.connect(self.click_radar_turn_add)  # 云台旋转速度增加
        self.pushButton_radar_turn_reduce.clicked.connect(self.click_radar_turn_reduce)  # 云台旋转速度减少

        self.comboBox_radar_scan.currentIndexChanged.connect(self.radar_scan_send)  # 雷达指令发送
        self.comboBox_radar_turn.currentIndexChanged.connect(self.radar_turn_send)  # 云台 按钮

        self.pushButton_exit.clicked.connect(self.close)  #退出系统 按钮
        self.pushButton_historical_data.clicked.connect(self.another_window_historical_data)  # 历史数据
        self.pushButton_time_registration.clicked.connect(self.another_window_time_registration)  # 时间配准
        self.pushButton_show_figure.clicked.connect(self.click_show_wall_figure)  # 显示图表细节

    def click_link(self):

        self.person_location = str(self.lineEdit_person_location.text())

        self.tcp_client_Thread = threading.Thread(target=self.tcp_client_start,daemon=True)  # socket关闭连接之后，client_th线程关闭，tcp_client_Thread也会关闭
        self.tcp_client_Thread.start()

        self.laser_tcp_client_Thread = threading.Thread(target=self.laser_tcp_client_start,daemon=True)  # socket关闭连接之后，client_th线程关闭，tcp_client_Thread也会关闭
        self.laser_tcp_client_Thread.start()

        self.fusion_thread_flag = True
        if self.comboBox_objtect_test.currentIndex() == 0:
            self.flush_thread = threading.Thread(target=self.single_queue_fusion0,
                                                 daemon=True)  # 当queue中没有数据时，flush_thread线程关闭，tcp_client_Thread也会关闭
            self.flush_thread.start()  # 启动  激光与雷达  数据的  融合
        if self.comboBox_objtect_test.currentIndex() == 1:
            self.flush_thread = threading.Thread(target=self.single_queue_fusion1,
                                                 daemon=True)  # 当queue中没有数据时，flush_thread线程关闭，tcp_client_Thread也会关闭
            self.flush_thread.start()  # 启动  激光与雷达  数据的  融合
        if self.comboBox_objtect_test.currentIndex() == 2:
            self.flush_thread = threading.Thread(target=self.multi_queue_fusion,
                                                 daemon=True)  # 当queue中没有数据时，flush_thread线程关闭，tcp_client_Thread也会关闭
            self.flush_thread.start()  # 启动  激光与雷达  数据的  融合



        self.laser_filter_thread_flag = True
        sound_filter_thread = threading.Thread(target=self.sound_filter, daemon=True)  # 定义时间配准线程
        sound_filter_thread.start()

        self.radar_filter_thread_flag = True
        radar_filter_thread = threading.Thread(target=self.radar_filter, daemon=True)  # 雷达滤波线程
        radar_filter_thread.start()

        self.link = True
        self.pushButton_unlink.setEnabled(True)
        self.pushButton_link.setEnabled(False)

    # 关闭连接
    def click_unlink(self):
        # self.radar_registration.stop()  # 关闭时间配准线程
        self.tcp_close()
        # self.radar_registration.stop()
        # print('tcp_client_Thread',self.tcp_client_Thread.isAlive())
        # print('laser_tcp_client_Thread',self.laser_tcp_client_Thread.isAlive())
        # print('flush_thread',self.flush_thread.name, self.flush_thread.isAlive())
        # print('radar_registration',self.radar_registration.name, self.radar_registration.isAlive())
        self.link = False
        self.pushButton_unlink.setEnabled(False)
        self.pushButton_link.setEnabled(True)

    # 重新获取IP按键 得到本机ip
    def click_get_ip(self):
        """
        pushbutton_get_ip控件点击触发的槽
        :return: None
        """
        # 获取本机ip
        self.lineEdit_ip_local.clear()
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        try:
            s.connect(('8.8.8.8', 80))
            my_addr = s.getsockname()[0]
            self.lineEdit_ip_local.setText(str(my_addr))
        except Exception as ret:
            # 若无法连接互联网使用，会调用以下方法
            try:
                my_addr = socket.gethostbyname(socket.gethostname())
                self.lineEdit_ip_local.setText(str(my_addr))
            except Exception as ret_e:
                self.signal_write_msg.emit("无法获取ip，请连接网络！\n")
        finally:
            s.close()

    # 显示图表
    def click_show_wall_figure(self):
        wall_list_x = self.myfigure_fusion.wall_x
        wall_list_y = self.myfigure_fusion.wall_y
        fusion_one_object_x = self.myfigure_fusion.one_object_x
        fusion_one_object_y = self.myfigure_fusion.one_object_y

        if wall_list_x != None :
            plt.scatter(wall_list_x, wall_list_y, marker='|', c='k', s = 1, linewidths=3)
        if fusion_one_object_x != None:
            plt.scatter(fusion_one_object_x, fusion_one_object_y, marker='.', c='r', cmap='jet', s=1, linewidths=None)
        plt.xlim(-10, 10)
        plt.ylim(0, 60)
        plt.show()

        self.another_location = locationUi(self.radar_object_list_ui,self.laser_history_point_list,self.fusion_object_list_ui ,wall_list_x,wall_list_y)
        self.another_location.show()

    # 清空接收区屏幕
    def click_clear(self):
        """
        pushbutton_clear控件点击触发的槽
        :return: None
        """
        self.clear_queue()
        self.fusion_history_point_list = []
        self.radar_history_point_list = []
        self.laser_history_point_list = []
        # 清空接收区屏幕
        # self.myfigure_rader.wall_x = None
        # self.myfigure_rader.wall_y = None
        self.object_radar_x = []
        self.object_radar_y = []

        # self.myfigure_fusion.wall_x = None
        # self.myfigure_fusion.wall_y = None
        self.object_fusion_x = []
        self.object_fusion_y = []

        self.object_laser_x = []
        self.object_laser_y = []

        self.myfigure_rader.updata_figure( name= 'Radar')
        self.myfigure_laser.updata_figure( name= 'Laser')
        self.myfigure_fusion.updata_figure_fusion( name= 'Fusion')

        self.textBrowser_recv_radar.clear()
        self.textBrowser_recv_laser.clear()
        self.textBrowser_recv_fusion.clear()

    # 云台速度增加
    def click_radar_turn_add(self):
        radar_turn_index = self.comboBox_radar_turn.currentIndex()
        if radar_turn_index != 0:
            self.radar_turn_speed = self.radar_turn_speed + 1
            if (self.radar_turn_speed >= 0) & (self.radar_turn_speed <= 64):
                self.radar_turn_add_reduce()
            else:
                if self.radar_turn_speed > 64:
                    self.radar_turn_speed = 64
                if self.radar_turn_speed < 0:
                    self.radar_turn_speed = 0
                QtWidgets.QMessageBox.warning(self, '速度', "速度已到极限！", QtWidgets.QMessageBox.Yes)
        else:
            msg = '穿墙雷达云台不可旋转\n'
            self.signal_write_rader_msg.emit(msg)

    # 云台速度减少
    def click_radar_turn_reduce(self):
        radar_turn_index = self.comboBox_radar_turn.currentIndex()
        if radar_turn_index != 0:
            self.radar_turn_speed = self.radar_turn_speed - 1
            if (self.radar_turn_speed >= 0) & (self.radar_turn_speed <= 64):
                self.radar_turn_add_reduce()
            else:
                if self.radar_turn_speed > 64:
                    self.radar_turn_speed = 64
                if self.radar_turn_speed < 0:
                    self.radar_turn_speed = 0
                QtWidgets.QMessageBox.warning(self, '速度', "速度已到极限！", QtWidgets.QMessageBox.Yes)
        else:
            msg = '穿墙雷达云台不可旋转\n'
            self.signal_write_rader_msg.emit(msg)

    # 重写退出事件
    def closeEvent(self, event):
        ok = QtWidgets.QPushButton()
        cancel = QtWidgets.QPushButton()
        msg = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, u'关闭', u'是否关闭！')
        msg.addButton(ok, QtWidgets.QMessageBox.ActionRole)
        msg.addButton(cancel, QtWidgets.QMessageBox.RejectRole)
        ok.setText(u'确定')
        cancel.setText(u'取消')
        if msg.exec_() == QtWidgets.QMessageBox.RejectRole:
            event.ignore()
        else:
            try:
                if (self.radar_registration.isAlive() == True):
                    self.radar_registration.stop()  # 关闭时间配准线程
            except:
                pass
            event.accept()

    # 开另外一个窗口
    def another_window_historical_data(self):
        """
        开启一个新的窗口的方法
        :return:
        """
        # 弹出一个消息框，提示开启了一个新的窗口
        QtWidgets.QMessageBox.warning(self, '历史数据', "已经开启了历史数据查询！", QtWidgets.QMessageBox.Yes)
        person_location = "（1,1);(2,2);(3,3);(4,4);"
        self.another_historical_data = Ui_table_history(person_location)
        self.another_historical_data.show()

    def another_window_time_registration(self):
        """
        开启一个新的窗口的方法
        :return:
        """
        # 弹出一个消息框，提示开启了一个新的窗口
        # QtWidgets.QMessageBox.warning(self, '时间配准', "已经开启了时间配准！", QtWidgets.QMessageBox.Yes)
        # self.another_time_registration = Ui_table_time()
        # self.another_time_registration.show()

        self.another_registration = locationUi_2(self.radar_fusion_time, self.laser_fusion_time, self.corner_x, self.corner_y )
        self.another_registration.show()


if __name__ == '__main__':
    app = QtWidgets.QApplication(sys.argv)
    ui = MainWindow(1)
    ui.show()
    sys.exit(app.exec_())
